/**
 * Created by Dell on 2017.10.31.
 */
var Token = '';
var reg_select;
var chr_select;
var regInfo={},chrInfo={};
var userId_ = JSON.parse($.cookie('userInfo')).userId;
$(function(){
    console.log(JSON.parse($.cookie('userInfo')))
    $.when(getChrSelect(),getRegSelect()).done(getAllUserInfo(userId_))

    //增加用户
    $('.addNewUser').click(function(){
        $('.popup_main .tit b').html('添加用户信息')
        $('.confirm').attr('type','add');
        $('.editorPopup').show();
        $('.editorPopup').find('input').each(function(){
            $(this).val('');
        });
        reg_select.setValue('001');
        chr_select.setValue('071');
    });

    // 更新用户
    $('#info').on('click','.update',function(){
        var userId = $(this).attr('userId');
        $('.confirm').attr('type','update');
        $('.popup_main .tit b').html('修改用户信息')
        $('.editorPopup').show();
        getUserInfo(userId);

    });

    //确认
    $('.confirm').click(function(){
        var type = $(this).attr('type');
        var data = {};
        $('.popup_main').find('input').each(function(){
            data[$(this).attr('name')] = $(this).val();
        });
        data.region_id = reg_select.getValue();
        data.chr_id = chr_select.getValue();
        var sMobile = $('input[name="tel"]').val();
        var pattern = /^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/;
        if(!(pattern.test(sMobile))){
            $.toast({
                text: '手机号码不正确！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
            return
        }
        if($('.passWord1').val() != '' && $('.passWord2').val() != '' && $('.passWord1').val() === $('.passWord2').val()){
            if(type == 'add'){    //增加用户
                addUser(data)
            }
            if(type == 'update'){   //修改用户
                data.userId = $('.confirm').data('userId');
                updateUser(data)
            }
            $('.editorPopup').hide();
        }
        else if($('.userName').val() == ''){
            $.toast({
                text: '用户名不能为空！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
        }else if($('.passWord1').val() == ''){
            $.toast({
                text: '密码不能为空！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
        }
        else {
            $.toast({
                text: '密码不一致！',
                icon: 'info',
                position: "mid-center",
                stack: false,
                allowToastClose: false,
                loader: false,
                bgColor: "red",
                textColor: "#fff",
                timeout: 2000,
            });
        }
    });


    //删除用户
    $('#info').on('click','.delete',function(){
        var userId = $(this).attr('userId');
        $.confirmWin({
            width:300,
            height:120,
            title:"删除",
            text:"<div class='removeWarnContent'>您确定要删除该用户吗？</div>",
            btnVal:"确定",
            submitFn:function(){
                //$(this).parent().parent().remove();
                deleteUser(userId)
            }
        });
    });

    $('#info').on('click','input',function(){
        //console.log($(this).attr('userId'));
        //console.log($(this).is(':checked'));
        var userId = $(this).attr('userId');
        var authPrior;
        if($(this).is(':checked') == true){
            authPrior = '1'
        }else{
            authPrior = '2'
        }
        updateUser_P(userId,authPrior)
    });

    $('.close,.cancel').click(function(){
        $('.editorPopup').hide();
    });

});

var filterVal = function(val){
    if(val == null || val == '') return '暂无信息'
    else return val
};
var filterTime = function(tm){
    if(tm == '' || tm == null){
        return '暂未登录'
    }else return new Date(tm).Format('yyyy-MM-dd hh:mm')
};


// 得到乡镇
function getRegSelect (){
    $.ajax({
        url: config.serviceUrl+ "/api/Region",
        type: "post",
        data:{
            "DATA": {
                "ID": "000",
                "Token" : Token,
            },
        },
        dataType: "json",
        success: function (jsonData) {
            if(jsonData !=null){
                var reg = jsonData.Region;
                var regsult = '';
                var regListsSult = '';
                regsult +='<option value="000">所有乡镇</option>';
                regInfo['000'] = '所有乡镇';
                for(var i=0; i<reg.length;i++){
                    regsult +='<option value="'+ reg[i].Region_ID+'">'+ reg[i].Region_Name +'</option>';
                    regInfo[reg[i].Region_ID] = reg[i].Region_Name;
                }
                reg_select = $('#reg_select').append(regsult).customSelect({
                    width:170,
                    lineHeight:28,
                });

            }
        }
    })

}


// 得到主管单位
function getChrSelect (){
    $.ajax({
        url: config.serviceUrl+ "/api/Chr",
        type: "post",
        data:{
            "DATA": {
                "Prefix": "071",
                "Token" : Token,
            }
        },
        dataType: "json",
        success: function (jsonData) {
            if(jsonData !=null){
                var chr = jsonData.CHR;
                var chrsult = '';
                chrListsSult = '';
                chrsult +='<option value="071">所有单位</option>';
                chrInfo['071'] = '所有单位';
                for(var i=0; i<chr.length;i++){
                    chrsult +='<option value="'+ chr[i].CHR_ID+'">'+ chr[i].CHR_Name +'</option>';
                    chrInfo[chr[i].CHR_ID] = chr[i].CHR_Name;
                }
                chr_select = $('#chr_select').append(chrsult).customSelect({
                    width:170,
                    lineHeight:28,
                });
            }
        }
    })
}

//获取所有用户信息
var getAllUserInfo = function(userId){
    var url = config.baseUrl + '/user/getUserInfo.do';
    $.ajax({
            url: url,
            type: "post",
            data:{
                userId:userId
            },
            dataType: "json",
            success: function (data) {
                if(data.code === 1){
                    var fa = data.data;
                    var str = '<thead><tr> <th>用户名</th> <th>真实姓名</th> <th>所属乡镇</th> <th>所属单位</th> <th>电话号码</th> ' +
                        '<th>管理权限</th> <th>最近登录</th> <th>操作</th> </tr></thead><tbody>';
                    for(var i = 0;i<fa.length;i++){
                        var chrid = fa[i].chr_id;
                        var regid = fa[i].region_id;
                        if(fa[i].userName == 'admin') continue;
                        str += '<tr> ' +
                            '<td>'+ filterVal(fa[i].userName)+'</td> ' +
                            '<td>'+ filterVal(fa[i].realName)+'</td> ' +
                            '<td>'+ filterVal(regInfo[regid])+'</td> ' +
                            '<td>'+ filterVal(chrInfo[chrid])+'</td> ' +
                            '<td>'+ filterVal(fa[i].tel)+'</td> ' +
                            '<td ><input type="checkbox" name="'+ fa[i].authPrior+'" userId="'+fa[i].userId +'"></td> ' +
                            '<td>'+ filterTime(fa[i].tokenTime)+'</td> ' +
                            '<td><ul class="editor"> ' +
                            '<li class="update" userId="'+fa[i].userId +'"></li> ' +
                            '<li class="delete" userId="'+fa[i].userId +'"></li> ' +
                            '</ul></td> ' +
                            '</tr>'
                    }
                    str += '</tbody>'
                    $("#info").empty();
                    $('#info').html('<table class="infoTable">'+str +'</table>');
                    $('.infoTable input').each(function(){
                        if($(this).attr('name') == '1'){
                            $(this).attr('checked','true');
                        }else{
                            $(this).remove('checked');
                        }
                    });
                    var infoHeight = $('.content').height() - $('.top').height() - 20;
                    $('#info').height(infoHeight);
                    var colsWidth = ['10%','10%','15%','15%','15%','10%','15%','10%'];
                    var colsDataType=["string","string","string","string","number","string","date","number"];
                    var colsCanSort=[true,true,true,true,true,true,true,false];
                    $(".infoTable").fixHeaderTable({
                        colsWidth:colsWidth,
                        colsDataType:colsDataType,
                        colsCanSort:colsCanSort,
                        height:infoHeight
                    });
                    $(".fixHeaderTable_mainTableWrap").mCustomScrollbar({
                        scrollButtons:{enable:true},
                        theme:"inset-2-dark",
                        axis:"xy",
                        autoHideScrollbar:true,
                        setLeft:0,
                        mouseWheel:true,
                        setTop:"px"
                    });
                }
            }
        })
};

//获取单个用户信息
var getUserInfo = function(userId){
    var url = config.baseUrl + '/user/getOneUser.do';
    $.ajax({
        url: url,
        type: "post",
        data:{
            userId:userId
        },
        dataType: "json",
        success: function (jsondata) {
            if(jsondata.code === 1){
                var fa = jsondata.data;
                $('.popup_main').find('input').each(function(){
                    if(fa[$(this).attr('name')]){
                        $(this).val(fa[$(this).attr('name')])
                    }else{
                        $(this).val('')
                    }

                });
                reg_select.setValue(fa.region_id);
                chr_select.setValue(fa.chr_id);
                $('.confirm').data('userId',userId)
            }
        }
    })
};

//删除用户
var deleteUser = function(userId){
    var url = config.baseUrl + '/user/deleteUser.do';
    $.ajax({
        url: url,
        type: "post",
        data:{
            userId:userId
        },
        dataType: "json",
        success: function (jsondata) {
            if(jsondata.code === 1){
                getAllUserInfo(userId_);
                $.toast({
                    text: '删除用户成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3e8dfd",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }else{
                $.toast({
                    text: '删除用户失败！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }
        }
    })
};

//更新用户
var updateUser = function(data){
    var url = config.baseUrl + '/user/updateUser.do';
    $.ajax({
        url: url,
        type: "post",
        data:data,
        dataType: "json",
        success: function (jsondata) {
            if(jsondata.code === 1){
                getAllUserInfo(userId_);
                $.toast({
                    text: '修改用户信息成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3e8dfd",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }else{
                $.toast({
                    text: '修改用户信息失败！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }
        }
    })
};

//增加用户
var addUser = function(data){
    var url = config.baseUrl + '/user/addUser.do';
    $.ajax({
        url: url,
        type: "post",
        data:data,
        dataType: "json",
        success: function (jsondata) {
            if(jsondata.code === 1){
                getAllUserInfo(userId_);
                $.toast({
                    text: '添加成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3e8dfd",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }else{
                $.toast({
                    text: '添加失败！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }
        }
    })
};

//更新用户权限
var updateUser_P = function(userId,authPrior){
    var url = config.baseUrl + '/user/updateUser.do';
    $.ajax({
        url: url,
        type: "post",
        data:{
            userId:userId,
            authPrior:authPrior,
        },
        dataType: "json",
        success: function (jsondata) {
            if(jsondata.code === 1){
                getAllUserInfo(userId_);
                $.toast({
                    text: '修改权限成功！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "#3e8dfd",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }else{
                $.toast({
                    text: '修改权限失败！',
                    icon: 'info',
                    position: "mid-center",
                    stack: false,
                    allowToastClose: false,
                    loader: false,
                    bgColor: "red",
                    textColor: "#fff",
                    timeout: 2000,
                });
            }
        }
    })
};














